package com.kingsoft.miot.bridge.controller;

import java.util.List;
import java.util.concurrent.CompletableFuture;

import com.alibaba.fastjson.JSONObject;
import com.kingsoft.miot.bridge.pojo.hotel.HouseInfo;
import com.kingsoft.miot.bridge.pojo.house.HouseVo;
import com.kingsoft.miot.bridge.utils.ValidationUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.kingsoft.miot.bridge.common.CommonResult;
import com.kingsoft.miot.bridge.controller.req.HouseReqBody;
import com.kingsoft.miot.bridge.controller.resp.HouseInfoResp;
import com.kingsoft.miot.bridge.controller.resp.PageResult;
import com.kingsoft.miot.bridge.service.HouseService;

/**
 * 家庭 户 控制器
 */
@RestController
public class HouseController {

    private static final Logger LOGGER = LoggerFactory.getLogger(HouseController.class);

    @Autowired
    private HouseService houseService;

    /**
     * 通过酒店id 获取房间返回信息列表
     *
     * @param id
     * @param pageRequest
     * @return
     */
    @RequestMapping(value = "/data/hotel/{id}/house", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    public String getHouseListByHotelId(@PathVariable String id, @RequestBody HouseReqBody pageRequest) {
        PageResult<HouseInfoResp> pageResult = null;
        try {
            if (StringUtils.isBlank(id) || pageRequest == null) {
                LOGGER.error("请求参数非法！");
                return CommonResult.returnJson(false, 400, "参数校验未通过。");
            }
            // 获取分页数据
            pageResult = houseService.findHouseByPageAndhotelId(Integer.valueOf(id), pageRequest.getPage(),
                    pageRequest.getSize(), pageRequest.getRoom_num(), pageRequest.getOrders());

        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("未获取到房间信息列表。");
            return CommonResult.returnJson(false, 500, "获取家庭（户）信息列表失败。");
        }
        List<HouseInfoResp> item_list = pageResult.getItem_list();
        return item_list == null || item_list.size() == 0 ? CommonResult.returnJson(false, 200, "获取家庭（户）信息失败。")
                : JSON.toJSONString(item_list);
    }

    /**
     * 获取酒店房屋的详细house(户)的详细信息
     *
     * @param id
     * @param house_id
     * @return
     */
//	@RequestMapping(value = "/data/hotels/{id}/house/{house_id}", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
//	public String getHouseInfoDetail(@PathVariable String id, @PathVariable String house_id) {
//		if (!NumberUtils.isDigits(id) || !NumberUtils.isDigits(house_id)) {
//			LOGGER.error("hotel_id或者house_id为空。");
//			return CommonResult.returnJson(false, 400, "hotel_id或者house_id为空。");
//		}
//		HouseInfoResp houseInfoResp = null;
//		try {
//			houseInfoResp = houseService.getByHotelInfoIdAndHouseInfoId(Integer.valueOf(id), Integer.valueOf(house_id));
//		} catch (Exception e) {
//			LOGGER.error("获取house信息失败。");
//			return CommonResult.returnJson(false, 500, "获取house信息失败。");
//		}
//		if (houseInfoResp == null) {
//			return CommonResult.returnJson(false, 200, "获取house信息失败。");
//		}
//		return JSON.toJSONString(houseInfoResp);
//	}
//
    /**
     * 获取房间日志
     * @param id
     * @param house_id
     * @return
     */
//	@RequestMapping(value = "/data/hotels/{id}/houses/{house_id}/logs", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
//	public String getHouseLog(@PathVariable String id, @PathVariable String house_id) {
//		
//	}


    /**
     * 创建房间
     * @param id
     * @return
     */
//	@RequestMapping(value = "/data/hotels/{id}/house/create_house", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
//	public String addHouseToHotel(@PathVariable String id) {
//		
//	}


    /**
     * 房间管理-房间信息列表
     * 请求方式：POST
     *
     * @param params
     * @return
     */
    @RequestMapping(value = "/data/hotels/{id}/houses", method = RequestMethod.POST,
            produces = {"application/json;charset=UTF-8"})
    public CompletableFuture<String> findHouseListByHouseNo(@RequestBody JSONObject params, @PathVariable int id) {
        params.put("id", id);
        return CompletableFuture.supplyAsync(() -> {
            try {
                ModelMap modelMap = houseService.findHouseListByHouseNo(params);
                LOGGER.info("房间管理-房间信息列表返回值->" + modelMap);
                return CommonResult.jsonString(modelMap);
            } catch (Exception e) {
                LOGGER.error(e.getMessage());
            }
            return CommonResult.returnJson(false, 200, "获取houseList列表失败");
        });
    }

    /**
     * 房间管理-某个房间信息详情
     * 请求方式：GET
     *
     * @return
     */
    @RequestMapping(value = "/data/hotels/{id}/house/{house_id}",
            produces = {"application/json;charset=UTF-8"}, method = RequestMethod.GET)
    public CompletableFuture<String> houseDetail(@PathVariable int id, @PathVariable int house_id) {
        LOGGER.info("结果是" + id + house_id);
        return CompletableFuture.supplyAsync(() -> {
            HouseInfo houseInfo = houseService.findHouseByHouseId(id, house_id);
            if (null != houseInfo) {
                HouseVo houseVo = new HouseVo(houseInfo.getHouse_info_id(),
                        houseInfo.getHouse_info_num(), houseInfo.getControl_unit_id(), houseInfo.getHouse_info_floors_total_num(),
                        houseInfo.getHouse_info_devices_total_num(), houseInfo.getHouse_info_devices_online_num(),
                        houseInfo.getUser_mobile(), houseInfo.getHouse_info_status() == 0 ? ValidationUtils.getHouseStatus(0) : ValidationUtils.getHouseStatus(1), houseInfo.getHouse_info_control_times(),
                        houseInfo.getHouse_info_history_times(), houseInfo.getLast_login_time(), houseInfo.getLast_operate_time());
                LOGGER.info("房间管理-某个房间信息详情->" + houseVo);
                return CommonResult.jsonString(houseVo);
            }
            return CommonResult.returnJson(false, 200, "获取house信息失败。");
        });
    }


    /**
     * 房间管理-添加房间
     * 请求方式：POST
     *
     * @return
     */
    @RequestMapping(value = "/data/hotels/{id}/house/create_house",
            produces = {"application/json;charset=UTF-8"}, method = RequestMethod.POST)
    public CompletableFuture<String> insertHouse(@RequestBody JSONObject params, @PathVariable int id) {
        return CompletableFuture.supplyAsync(() -> {
            params.put("hotel_id", id);
            int count = houseService.insertBathHouse(params);
            return CommonResult.jsonString(count);
        });
    }

}
